package bb.lanxing.activity.bluetooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;

import bb.lanxing.lib.devices.api.DeviceManager;
import bb.lanxing.lib.devices.ble.BleCons;
import bb.lanxing.network.MyHttpClient;
import gov.nist.core.Separators;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseDisplayActivity;
import bb.lanxing.calc.data.DisplayPoint;
import bb.lanxing.lib.devices.api.ConnectionListener;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.DeviceContext;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import bb.lanxing.model.database.Device;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.view.BiciAlertDialogBuilder;

import org.json.JSONObject;

public class HeartRateStatusActivity extends BaseDisplayActivity implements ConnectionListener {
    private TextView batteryView;
    private TextView manufactureView;
    private TextView modelView;
    private TextView firmwareView;
    private Device device;
    private TextView heartrateView;
    private long lastEffectiveTime;
    private TextView nameView;
    private TextView unbindBtn;
    private Handler handler = new Handler();
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action == null) {
                return;
            }

            if (action.equals(BleCons.ACTION_BATTERY)
                    && intent.getIntExtra(BleCons.EXTRA_DEVICE_TYPE, 0) == SmartDevice.TYPE_HEARTRATE) {
                int intExtra = intent.getIntExtra(BleCons.EXTRA_BATTERY, 0);
                batteryView.setText(intExtra + Separators.PERCENT);
            }

            if (action.equals(BleCons.ACTION_DEVICE_INFORMATION)){
                if (intent.getIntExtra(BleCons.EXTRA_DEVICE_TYPE, 0) != SmartDevice.TYPE_HEARTRATE) {
                    return;
                }
                String stringExtra = intent.getStringExtra(BleCons.EXTRA_FIRMWARE_VERSION);
                if (stringExtra != null) {
                    firmwareView.setText(stringExtra);
                }
                String stringExtra2 = intent.getStringExtra(BleCons.EXTRA_MODEL);
                if (stringExtra2 != null) {
                    modelView.setText(stringExtra2);
                }
                String stringExtra3 = intent.getStringExtra(BleCons.EXTRA_MANUFACTURE);
                if (stringExtra3 != null) {
                    manufactureView.setText(stringExtra3);
                }
            }

            if (action.equals(BleCons.ACTION_READ_DEVICE_INFORMATION_RESULT)){

                String stringExtra4 = intent.getStringExtra(BleCons.EXTRA_MANUFACTURE);
                String stringExtra5 = intent.getStringExtra(BleCons.EXTRA_FIRMWARE_VERSION);
                String stringExtra6 = intent.getStringExtra(BleCons.EXTRA_MODEL);
                if (stringExtra4 == null || stringExtra5 == null || stringExtra6 == null
                        || stringExtra4.isEmpty() || stringExtra5.isEmpty() || stringExtra6.isEmpty()) {
                    requestDeviceInfo();
                }

                if (stringExtra4 != null) {
                    manufactureView.setText(stringExtra4);
                }

                if (stringExtra5 != null) {
                    firmwareView.setText(stringExtra5);
                }

                if (stringExtra6 != null) {
                    modelView.setText(stringExtra6);
                }
           }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (!DeviceHelper.isConnected(SmartDevice.TYPE_HEARTRATE)) {
            DeviceHelper.connect(this.device);
        } else {
            requestBattery();
            readDeviceInfo();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        DeviceHelper.unregisterConnectionStateListener(this);
    }

    public void requestBattery() {
        this.batteryView.postDelayed(() -> {
            Intent intent = new Intent(BleCons.ACTION_REQUEST_BATTERY);
            intent.putExtra(BleCons.EXTRA_DEVICE_TYPE, SmartDevice.TYPE_HEARTRATE);
            HeartRateStatusActivity.this.sendOrderedBroadcast(intent, null);
        }, 100L);
    }

    public void requestDeviceInfo() {
        Device device = this.device;
        if (device == null || device.getAddress() == null) {
            return;
        }
        Intent intent = new Intent(BleCons.ACTION_REQUEST_DEVICE_INFORMATION);
        intent.putExtra(BleCons.EXTRA_DEVICE_TYPE, SmartDevice.TYPE_HEARTRATE);
        intent.putExtra(BleCons.EXTRA_DEVICE_ADDRESS, device.getAddress());
        sendOrderedBroadcast(intent, null);
    }

    private void readDeviceInfo() {
        Device device = this.device;
        if (device == null || device.getAddress() == null) {
            return;
        }

        this.batteryView.postDelayed(() -> {
            if (device.getAddress() == null) {
                return;
            }
            Intent intent = new Intent(BleCons.ACTION_READ_DEVICE_INFORMATION);
            intent.putExtra(BleCons.EXTRA_DEVICE_TYPE, SmartDevice.TYPE_HEARTRATE);
            intent.putExtra(BleCons.EXTRA_DEVICE_ADDRESS, device.getAddress());
            sendOrderedBroadcast(intent, null);
        }, 100L);
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_heart_rate_status);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        DeviceHelper.registerConnectionStateListener(this);
        registerReceiver();
        Device byAddress = Device.getByAddress(getIntent().getStringExtra(BleCons.EXTRA_DEVICE_ADDRESS));
        this.device = byAddress;
        if (byAddress == null) {
            finish();
            return;
        }
        this.nameView.setText(byAddress.getName());

        this.unbindBtn.setOnClickListener(view -> HeartRateStatusActivity.this.unBoundDeviceConfirm());
    }

    public void unBoundDeviceConfirm() {
        new BiciAlertDialogBuilder(this)
                .setTitle(R.string.st_forget_sensor)
                .setMessage(R.string.st_are_you_sure_unbind)
                .setPositiveButton(R.string.mine_profile_dialog_btn_unbind, (dialogInterface, i) -> {
                    if (HeartRateStatusActivity.this.device.getDeviceNumber() > 0) {
                        MyHttpClient.deleteDevice(HeartRateStatusActivity.this.device.getDeviceNumber());
                    }
                    Device.deleteAll(Device.class, "address = ? and userId = ?",
                            device.getAddress(), String.valueOf(App.getContext().getUserId()));
                    App.getContext().disconnectDevice(SmartDevice.TYPE_HEARTRATE);
                    DeviceContext.startAndRefreshAutoConnector();
                    HeartRateStatusActivity.this.finish();
                })
                .setNegativeButton(R.string.str_sync_cancel, (dialogInterface, i) -> {
                }).show().setCanceledOnTouchOutside(true);
    }

    @Override
    public void onDestroy() {
        DeviceHelper.unregisterConnectionStateListener(this);
        BroadcastReceiver broadcastReceiver = this.broadcastReceiver;
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        super.onDestroy();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleCons.ACTION_BATTERY);
        intentFilter.addAction(BleCons.ACTION_HEARTRATE_DATAS);
        intentFilter.addAction(BleCons.ACTION_DEVICE_INFORMATION);
        intentFilter.addAction(BleCons.ACTION_READ_DEVICE_INFORMATION_RESULT);
        registerReceiver(this.broadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
    }

    private void uploadDeivceInfo() {
        MyHttpClient.uploadDevice(new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String str) {
                try {
                    device.setDeviceNumber(new JSONObject(str).getInt("deviceServerId"));
                    device.save();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, this.device);
    }

    @Override
    protected void onRefreshUI(DisplayPoint displayPoint) {
        this.heartrateView.setText(String.valueOf(displayPoint.getHeartrate(0)));
    }

    private void bindView(View view) {
        this.heartrateView = view.findViewById(R.id.heartrateView);
        this.nameView = view.findViewById(R.id.nameView);
        this.batteryView = view.findViewById(R.id.batteryView);
        this.manufactureView = view.findViewById(R.id.manufactureView);
        this.modelView = view.findViewById(R.id.modelView);
        this.firmwareView = view.findViewById(R.id.firmwareView);
        this.unbindBtn = view.findViewById(R.id.unbindBtn);
    }

    @Override
    public void onConnectionStateChanged(SmartDevice smartDevice, int i, int i2) {
        if (smartDevice.getAddress().equals(this.device.getAddress())) {
            if (i == DeviceManager.STATE_CONNECTED) {
                this.heartrateView.postDelayed(HeartRateStatusActivity.this::requestBattery, 100L);
                this.heartrateView.postDelayed(HeartRateStatusActivity.this::requestDeviceInfo, 100L);
            } else if (i == DeviceManager.STATE_DISCONNECTED) {
                finish();
            }
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean z) {
        super.onPointerCaptureChanged(z);
    }
}
